package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.PrimitiveType;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class AddTemporalActionExtension extends BaseUtiltiyActionExtension {

	protected static final String TEMPORAL = "javax.persistence.Temporal";

	protected static final String TEMPORAL_TYPE = "javax.persistence.TemporalType";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new AddTemporalAction());
	}

	protected void execute(Class clazz) {
		EList<NamedElement> list = clazz.getMembers();
		for (NamedElement namedElement : list) {
			if (namedElement instanceof Property) {
				execute((Property) namedElement);
			}
		}
	}

	protected void execute(Property property) {
		if (isDate(property)) {
			setTemporal(property, "DATE");
		}
		if (isTime(property)) {
			setTemporal(property, "TIME");
		}
		if (isTimestamp(property)) {
			setTemporal(property, "TIMESTAMP");
		}
	}

	private boolean isTimestamp(Property property) {
		PrimitiveType type = getPrimitiveType(property, "Timestamp");
		return property.getType().equals(type);
	}

	private boolean isTime(Property property) {
		PrimitiveType type = getPrimitiveType(property, "Time");
		return property.getType().equals(type);
	}

	private boolean isDate(Property property) {
		PrimitiveType type = getPrimitiveType(property, "Date");
		return property.getType().equals(type);
	}

	protected void setTemporal(NamedElement element, String type) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, TEMPORAL);
		if (stereotype != null) {
			element.applyStereotype(stereotype);
			Element e = ModelUtil.getProfileElement(element, TEMPORAL_TYPE);
			if (e != null) {
				if (e instanceof Enumeration) {
					element.setValue(stereotype, "value", ((Enumeration) e)
							.getOwnedLiteral(type));
				}
			}
			Console.getStream().println(
					"Added " + TEMPORAL + " stereotype - "
							+ element.getQualifiedName());
		}
	}

	private class AddTemporalAction extends BaseUtilityAction {
		private static final String LABEL = "Add Temporal Stereotypes";

		public AddTemporalAction() {
			super(LABEL);
		}
	}
}
